package com.tz.service;

import com.tz.dao.AccountDao;
import com.tz.entity.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;

//@Component
@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;

    public AccountServiceImpl() {
        System.out.println("AccountServiceImpl 空参构造...");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Transactional
    public String transfer(int from, int to, double amount) {
        //1.检查转出账户是否存在
        Account accFrom = accountDao.get(from);
        if (accFrom == null) {
            return "转出账户不存在!";
        }
        //2.检查转入账户是否存在
        Account accTo = accountDao.get(to);
        if (accTo == null) {
            return "转入账户不存在!";
        }
        //3.检查转出账户余额是否充足
        if (accFrom.getBalance() < amount) {
            return "转出账户余额不充足!";
        }
        //4.减操作
        accFrom.setBalance(accFrom.getBalance() - amount);
        accountDao.update(accFrom);
        //randomException();
        //5.加操作
        accTo.setBalance(accTo.getBalance() + amount);
        accountDao.update(accTo);
        return "转账成功";
    }

    private void randomException() {
        Calendar c = Calendar.getInstance();
//        int second = c.get(Calendar.SECOND);
        if (true) {
            throw new RuntimeException("自定义异常");
        }
    }


}
